package com.yc.javaee.多线程;

import java.util.ArrayList;
import java.util.List;

public class 生产者与消费者模式 {

    public static void main(String[] args) {

        Factory factory = new Factory();

        new Thread(()->{
            try {
                factory.product();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        Thread t = new Thread(()->{
            try {
                factory.consume();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "张三");
        t.setPriority(10);
        t.start();

        Thread t1 = new Thread(()->{
            try {
                factory.consume();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "李四");
        t1.setPriority(1);
        t1.start();
    }

}

class Factory {

    List<Object> store = new ArrayList<>();

    // 生产者
    synchronized void product() throws InterruptedException {
        while (true) {
            while (store.isEmpty()) {
                for (int i = 0; i < 10; i++) {
                    System.out.println("生产商品" + i);
                    store.add("商品" + i);
                    Thread.sleep(100);
                }
            }
            // wait, notify, notifyAll  都是 Object 提供的方法
            this.notifyAll();
            this.wait();
        }
    }

    //消费者   synchronized ==> 锁定了 this
    synchronized void consume() throws InterruptedException {
        while (true) {
            while (!store.isEmpty()) {
                String name = Thread.currentThread().getName();
                System.out.println(name + "消费"+store.remove(0));
                Thread.sleep(100);
            }
            // notiry 是随机通知一个线程, notifyAll 通知所有线程
            this.notifyAll();
            // 放弃同步锁, 在此等待, 等待其他线程通知我继续执行
            this.wait();
        }
    }
}
